<template>
  <div class="setting-container">
    <el-card class="setting-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="content">
        <el-form :model="userInfo" :rules="userInfoRules" ref="userInfoRef" label-width="200px">
          <el-form-item label="编号：">
            {{userInfo.id}}
          </el-form-item>
          <el-form-item label="手机：">
            {{userInfo.mobile}}
          </el-form-item>
          <el-form-item label="媒体名称：" prop="name">
            <el-input v-model="userInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="媒体介绍：" prop="intro">
            <el-input type="textarea" v-model="userInfo.intro"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveForm('userInfoRef')">保存设置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="avatar-box" width="50%">
        <el-avatar class="avatar" :src="userInfo.photo" shape="square" fit="cover">
        </el-avatar>
        <p style="padding: 0;line-height: 0" @click="$refs.file.click()">修改头像</p>
        <input type="file" name="" value="" hidden ref="file" @change="changeAvatar">
      </div>
    </el-card>
    <!-- 裁剪头像对话框 -->
    <el-dialog title="修改头像" :visible.sync="dialogVisible" width="30%" @opened="dialogOpen" @closed="dialogClosed">
      <div class="preview-image-box">
        <img class="preview-image" :src="imageUrl" alt="" ref="avatar">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadAvatar" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import Cropper from 'cropperjs'
  import 'cropperjs/dist/cropper.css'
  import globalBus from '@/utils/global-bus.js'
  import {
    getUseInfo,
    updateUseInfo,
    uploadAvatar
  } from '@/api/user.js'
  export default {
    name: 'Setting',
    data() {
      return {
        userInfo: {},
        searchForm: {
          name: '',
          intro: '',
          email: ''
        },
        loading: false,
        dialogVisible: false,
        imageUrl: '',
        cropper: null,
        userInfoRules: {
          name: [{
              required: true,
              message: '请输入媒体名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 7,
              message: '长度在 1 到 7 个字符',
              trigger: 'blur'
            }
          ],
          intro: [{
            required: true,
            message: '请输入媒体介绍',
            trigger: 'blur'
          }],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    created() {
      this.loadUseInfo()
    },
    methods: {
      loadUseInfo() {
        getUseInfo().then(res => {
          this.userInfo = res.data.data
        })
      },
      saveForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.searchForm.name = this.userInfo.name
            this.searchForm.intro = this.userInfo.intro
            this.searchForm.email = this.userInfo.email
            updateUseInfo(this.searchForm).then(res => {
              this.loadUseInfo()
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              globalBus.$emit('update-name', this.userInfo.name)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      changeAvatar() {
        const file = this.$refs.file
        this.imageUrl = window.URL.createObjectURL(file.files[0])
        this.dialogVisible = true
        this.$refs.file.value = ''
      },
      dialogOpen() {
        // 获取DOM节点
        const image = this.$refs['avatar']
        if (this.cropper) {
          this.cropper.replace(this.imageUrl)
          return
        }
        // 初始化裁剪器
        this.cropper = new Cropper(image, {
          aspectRatio: 1,
          viewMode: 1,
          dragMode: 'none',
          backgroud: false,
          movable: true,
          crop(event) {}
        })
      },
      dialogClosed() {
        //销毁裁剪器
        // this.cropper.destroy()
      },
      uploadAvatar() {
        this.loading = true
        this.cropper.getCroppedCanvas().toBlob(file => {
          const formData = new FormData()
          formData.append('photo', file)
          uploadAvatar(formData).then(res => {
            // this.userInfo.photo = window.URL.createObjectURL(file)
            this.loading = false
            this.userInfo.photo = res.data.data.photo
            globalBus.$emit('update-photo', this.userInfo.photo)
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '修改头像成功!'
            })
          })
        })


      }
    }
  }

</script>
<style lang="less" scoped>
  .setting-card {
    margin: 15px;
  }

  .content {
    float: left;
    width: 50%;
  }

  .avatar-box {
    text-align: center;
    padding-top: 70px;

    .avatar {
      width: 170px;
      height: 170px;
    }

  }

  .preview-image-box {
    .preview-image {
      display: block;
      max-width: 100%;
    }
  }

</style>
